<template>
  <div class="pg-canvas">
    <canvas
      id="el"
      width="300"
      height="300"
      @touchstart="touchstart"
      @touchmove="touchmove"
      @touchend="touchend"
    ></canvas>
  </div>
</template>

<script setup lang="ts" name="CanvasEl">
import { Toast } from 'vant'
const ctx = computed(() => {
  const canvas = document.querySelector('#el') as HTMLCanvasElement
  if (!canvas!.getContext) {
    Toast('您的浏览器不支持canvas标签，请升级！')
    return
  }

  return canvas!.getContext('2d') as CanvasRenderingContext2D
})
// const initCanvas = () => {
// ctx.fillStyle = '#ccc'
// 填充图形
// ctx.fillRect(10, 10, 50, 50)
// 描边图形
// ctx.value!.strokeRect(10, 10, 50, 50)
// 画图形的流程
//   ctx.beginPath()
//   ctx.moveTo(100, 100)
//   ctx.lineTo(50, 100)
//   ctx.lineTo(50, 150)
//   ctx.closePath()
//   ctx.stroke()
// 画一个图片
// }

// const drawImage = () => {
//   const image = new Image();
//   image.src = Icon;
//   image.onload = () => ctx.value!.drawImage(image, 0, 0, 150, 300);
// };

const touchstart = (e: TouchEvent) => {
  const { pageX, pageY } = e.touches[0]
  ctx.value!.moveTo(pageX, pageY)
}
const touchmove = (e: TouchEvent) => {
  const { pageX, pageY } = e.touches[0]
  ctx.value!.lineTo(pageX, pageY)
  ctx.value!.stroke()
}
const touchend = (e: TouchEvent) => {
  const { pageX, pageY } = e.changedTouches[0]
  console.log('touchEnd:', pageX, pageY)
}

// 刮刮卡
const ty = () => {
  ctx.value!.beginPath()
  ctx.value!.fillStyle = '#ccc'
  ctx.value!.fillRect(0, 0, 300, 300)
  ctx.value!.globalCompositeOperation = 'destination-out' // 目标经过的地方和canvas交汇的地方canvas颜色为透明
  ctx.value!.lineWidth = 20
  ctx.value!.lineCap = 'round'
}
onMounted(() => {
  ty()

  // const a = document.createElement('a')
  // a.download = '777'
  // a.href = 'https://img.life.cntaiping.com/cms/test/99/16644180594211.zip'
  // a.click()
})
</script>

<style lang="scss" scoped>
.pg-canvas {
  position: relative;
  height: 100%;

  &_image {
    width: 300px;
    height: 300px;
  }

  #el {
    position: absolute;
    top: 0;
    left: 0;
    box-shadow: 0 0 5px red;
  }
}

.test-jsx {
  color: pink;
}
</style>
